package me.yuzho.study.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/** 自定义ThreadFactory，返回的线程默认为后台线程
 * @author yzhou-citrix
 *
 */
public class DaemonThreadFactory implements ThreadFactory {

    @Override
    public Thread newThread(Runnable r) {
        
        Thread t = new Thread(r);
        t.setDaemon(true);
        return t;
    }
    
    
    public static void main(String [] args) throws InterruptedException {
        
        ExecutorService exec = Executors.newCachedThreadPool(new DaemonThreadFactory());
         
        //for(int i=0; i<10; i++) {
        IntStream.range(0, 10).forEach(i -> {
            exec.execute(new SimpleDaemons());
        });
        //}
        exec.shutdown();
        
        System.out.println("All daemons started");
        TimeUnit.MILLISECONDS.sleep(500);
    }

}
